import i18nManager from "./managers/I18nManager";
import styleManager from "./managers/StyleManager";
import coursewareConfigManager from "./managers/CoursewareConfigManager";
import {stringUtils} from "../utils/stringUtils";
import {getPlayerConfig} from "../utils/playerUtils";
import {initAmoeba} from "./amoeba";
import {urlUtils} from "../utils/urlUtils";
import jQuery from 'jquery';

let midwareInit = false;

export let Midware = {};
export const MidwareConfig = {
    BasePath: '',                       //中间层加载的基础路径
    PlayerReleaseNumber: '000000',      //定制播放器的发布号
    ConfigurationPath: 'configuration', //配置文件的路径,相对基础路径
    LanguageBasePath: 'languages',      //国际化文件的路径,相对基础路径
    StyleBasePath: 'style',             //样式库的路径,相对附件路径
    AssetsBasePath: 'assets',           //附件的路径,相对基础路径
    ComponentBasePath: 'js-library',    //控件库的路径,相对基础路径
    ExtendBasePath: 'extends',          //扩展模块的路径,相对附件路径
    RunEnvironment: 'product'           //当前运行环境
};
//定制播放器的配置
export const CustomPlayerConfig = {
    Presenters: {},
    Scripts: {}
};

//设置版本号
Object.defineProperty(Midware, 'version', {value: "1.2.7"});

Object.defineProperty(Midware, 'globalConfig', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function (options) {
        if (typeof options.BasePath === 'string') {
            MidwareConfig.BasePath = options.BasePath;
        }
        if (typeof options.LanguageBasePath === 'string') {
            MidwareConfig.LanguageBasePath = options.LanguageBasePath;
        }
        if (typeof options.AssetsBasePath === 'string') {
            MidwareConfig.AssetsBasePath = options.AssetsBasePath;
        }
        if (typeof options.ComponentBasePath === 'string') {
            MidwareConfig.ComponentBasePath = options.ComponentBasePath;
        }
        if (typeof options.PlayerReleaseNumber === 'string') {
            MidwareConfig.PlayerReleaseNumber = options.PlayerReleaseNumber;
        }
        if (typeof options.NativeBridgeClass === 'string') {
            Object.defineProperty(MidwareConfig, 'NativeBridgeClass', {value: options.NativeBridgeClass});
        }
        Object.defineProperty(MidwareConfig, 'Online', {value: urlUtils.isHttpAddress(MidwareConfig.BasePath)});
        if (options.RunEnvironment !== undefined && typeof options.RunEnvironment === 'string') {
            if (options.RunEnvironment === 'product' || options.RunEnvironment === 'development') {
                MidwareConfig.RunEnvironment = options.RunEnvironment
            }
        }
    }
});

Object.defineProperty(Midware, 'startup', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function (options) {
        if (midwareInit === true) {
            console.warn("Middleware has been initialized!");
            return;
        }
        midwareInit = true;
        if (typeof options !== 'object') {
            console.warn('startup option error');
            return;
        }
        const i18n = jQuery.extend({
                configPath: stringUtils.urlJoin(MidwareConfig.BasePath, MidwareConfig.LanguageBasePath),
                configFile: 'language.json',
                load: true
            }, options.i18n),
            courseware = jQuery.extend({
                configPath: stringUtils.urlJoin(MidwareConfig.BasePath, MidwareConfig.ConfigurationPath),
                configFile: 'coursesubject.json',
            }, options.courseware),
            extend = jQuery.extend({context: "_", load: true}, options.extend),
            style = jQuery.extend(
                {
                    configPath: stringUtils.urlJoin(MidwareConfig.BasePath, MidwareConfig.AssetsBasePath, MidwareConfig.StyleBasePath),
                    configFile: 'style.config.json',
                    containVersion: false,
                    load: true
                }, options.style),
            async = options.async === undefined ? true : options.async;
        //加载定制播放器的配置
        const file = (options && options.file) ? options.file : "config.json";
        const code = (options && options.code) ? options.code : undefined;
        const version = (options && options.version) ? options.version : undefined;
        getPlayerConfig(MidwareConfig, code, version, file, async)
            .done((config) => {
                if (config.presenters) {
                    for (let key in config.presenters) {
                        const tempConfig = config.presenters[key];
                        CustomPlayerConfig.Presenters[key] = {
                            code: tempConfig.presenterCode,
                            version: tempConfig.version,
                            release: tempConfig.releaseNum
                        }
                    }
                }
                if (config.script) {
                    for (let i = 0, len = config.script.length; i < len; i++) {
                        const tempConfig = config.script[i];
                        CustomPlayerConfig.Scripts[tempConfig.name] = {
                            code: tempConfig.name,
                            version: tempConfig.version,
                            release: tempConfig.releaseNum
                        }
                    }
                }
            })
            .fail(() => {
                console.error("Unable to read the custom player's configuration file");
            });
        //存在i18n的配置
        if (i18n.load) {
            console.info("===Execute multi-language manager to initialization===");
            const configPath = i18n.configPath || MidwareConfig.LanguageBasePath;
            const configFile = i18n.configFile || 'language.json';
            mergeToMidware('i18nManager', i18nManager);
            i18nManager.loadConfig(configPath, configFile, async);
        }
        //存在扩展模块的配置
        if (extend.load) {
            console.info("===Execute the expansion module manager to initialize===");
            const defaultContext = extend.context || "_";
            const baseUrl = stringUtils.urlJoin(
                MidwareConfig.BasePath,
                MidwareConfig.AssetsBasePath,
                MidwareConfig.ExtendBasePath);
            //初始化扩展模块功能
            initAmoeba();
            //进行扩展模块的配置
            Midware.extendModule.config({
                context: defaultContext,
                baseUrl: baseUrl
            });
        }
        //存在样式库模块的配置
        if (style.load) {
            console.info("===Execute the style library module manager to initialize===");
            const styleConfigPath = style.configPath || stringUtils.urlJoin(MidwareConfig.BasePath,
                    MidwareConfig.AssetsBasePath, MidwareConfig.StyleBasePath);
            const styleConfigFile = style.configFile || 'style.config.json';
            const containVersion = style.containVersion || false;
            //将StyleManager加入Midware对象中
            mergeToMidware('styleManager', styleManager);
            styleManager.loadConfig(styleConfigPath, styleConfigFile, async, containVersion);
        }
        //加载颗粒配置
        console.info("===Load courseware object config===");
        const configPath = courseware.configPath || MidwareConfig.ConfigurationPath,
            configFile = courseware.configFile || 'coursesubject.json';
        coursewareConfigManager.loadConfig(configPath, configFile, async);
    }
});

export function mergeToMidware(name, fn) {
    if (typeof fn === 'function') {
        Object.defineProperty(Midware, name, {
            enumerable: true,
            writable: false,
            configurable: false,
            value: fn
        });
    } else {
        if (!Midware[name]) {
            Midware[name] = fn;
        }
    }
}